import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DecodeTest {
    private static final String DECRYPTION_KEY = "5319916a431be598b4c7eabd4d6b2f1684d928fa"; // 16 字节的密钥
    public static void main(String[] args) {
      String session = "0c3CkHll2HjXsf4LRWml2CSX4p0CkHlI";
        String s = decryptData("2DBcz58L+7fghGKZNdwRr6xD41gubzpRWoka6XVVq129vDWqTxWJtOqkfF2uJ6oVyR4qDBxQKEy4wVpthOAjEdSR4eyOjjuMRd6LltiluQjYv3xnk7jZx/ZOdH0sF8SLxuYiCSBHwPz19kMOnCyYA1W78imFDieHXVoKTg7Wf0HcVNqv44veO2K1kOyW9d3ZRhW6Wsy1ff12G2TEdBpmPqT75OFaw4gI1nG4KsArsh3nf7iGNnSHHXNVWjCe651IQcvweVKOZMoZ1zEqp+ngzWwEnu/UB//reOku19gmq1qcKb+pMeyGPInT0TJn1c6XJ8vCztDGJrmbULFkNlYQXWAQNnvdM/hPdDxqXWnrz7FTqH9fXoYg99qmJx4Ze+L7RfrwdgGab7qDjIVUta1m9XDzaip39mx2c338Bqn2cbpM18eWOtEtiLyQD4wMjw+W",
                getSessionKey(session),
                "TmtjsLj6qud9rgRLA/9quQ==");
        System.out.println(s);
    }

    public static String getSessionKey(String code) {
        try {
            // 微信服务器的接口地址
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxba94b6b4c5082b0e&secret=23b976a723d5a12fac8745b1ac5db43c&js_code=" + code + "&grant_type=authorization_code";

            // 创建URL对象
            URL obj = new URL(url);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为GET
            con.setRequestMethod("GET");

            // 获取响应码
            int responseCode = con.getResponseCode();
            if (responseCode == 200) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析响应JSON数据，获取session_key
                // 这里可以使用JSON解析库，如Jackson或Gson
                // 假设使用Jackson，示例代码如下：
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(response.toString());
                return jsonNode.get("session_key").asText();
            } else {
                // 处理请求失败的情况
                System.out.println("请求微信服务器失败，响应码：" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        /**
         * 微信加密数据解密
         * @param encryptedData 加密数据
         * @param sessionKey 会话密钥
         * @param iv 初始向量
         * @return 解密后的数据
         * @throws Exception 解密异常
         */
        @SneakyThrows
        public static String decryptData(String encryptedData, String sessionKey, String iv) {
            // 将 Base64 编码的字符串解码为字节数组
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            // 创建 AES 密钥
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            // 创建初始向量
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            // 创建 Cipher 对象并初始化
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            // 解密数据
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

            // 将解密后的字节数组转换为字符串
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        }
}
